//
//  DetailsViewController.m
//  UEAssistant
//
//  Created by mac on 2017/7/24.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "DetailsViewController.h"
#import "ProductDetailsTableViewCell.h"
#import "ProgressViewOfProDD.h"
#import "DetailsModel.h"
#import "ACEExpandableTextCell.h"
#import <IQKeyboardManager.h>
#import <VTMagic.h>

#define remark_height [YhxUtility autoCalculateWidthOrHeight:MAXFLOAT width:Screen_Width-30*Radio fontsize:FLEXIBLE(15) content:detailsModel.remark] + 20

@interface DetailsViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,ACEExpandableTableViewDelegate>{

    CGFloat             _textView_height;
    CGFloat             _name_header_height;
    CGFloat             _cellHeight[2];
}

@property (nonatomic, strong) UITableView                   *tableView;
@property (nonatomic, strong) UIButton                      *edit;
@property (nonatomic, strong) UIButton                      *editF;
@property (nonatomic, strong) UITextView                    *productName;
@property (nonatomic, strong) NSArray                       *titles;
@property (nonatomic, strong) ProgressViewOfProDD           *progressView_All;
@property (nonatomic, strong) ProgressViewOfProDD           *progressView_proofread;
@property (nonatomic, strong) ProgressViewOfProDD           *progressView_edit;
@property (nonatomic, strong) ProgressViewOfProDD           *progressView_translate;
@property (nonatomic, strong) DetailsModel                  *model;
@property (nonatomic, strong) NSMutableArray                *types;
@property (nonatomic, strong) UITextView                    *textView;
@property (nonatomic, strong) UIImageView                   *penView;
@property (nonatomic, strong) UIImageView                   *penViewF;
@property (nonatomic, strong) UILabel                       *projectRemark;
@property (nonatomic, strong) UIButton                      *saveBt;

@property (strong, nonatomic)UIButton *backButton;//返回按钮

@end

@implementation DetailsViewController
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"Nav_返回"] forState:UIControlStateNormal];
        _backButton.frame = CGRectMake(0, 0, 20, 20);
        [_backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    self.magicController.navigationItem.rightBarButtonItem = nil;
    self.magicController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
    [self.tableView reloadData];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = NO;
    [_textView resignFirstResponder];
    [_productName resignFirstResponder];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.magicController.navigationItem.rightBarButtonItem = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initlizeDataSource];
    [self initlizeUserface];
}

- (void)initlizeDataSource{
    
    _name_header_height = 50*Radio;
    _titles = @[@"语种",@"文件数",@"原文字数",@"译文字数",@"译文标签",@"完成时间"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ProductDetailsTableViewCell" bundle:nil] forCellReuseIdentifier:productDetailsCell];
    _model = [[DetailsModel alloc]init];
  
    //截取标签
    _types = [NSMutableArray array];
    if (((NSString *)(detailsModel.dataSource_head[4])).length != 0) {
        NSArray *tempArr = [detailsModel.dataSource_head[4] componentsSeparatedByString:@","];
        NSLog(@"tempArr -- %@",tempArr);
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_types addObject:[obj substringFromIndex:NSMaxRange([obj rangeOfString:@"_"])]];
        }];
        NSString *string = [_types componentsJoinedByString:@"、"];
        [detailsModel.dataSource_head removeObjectAtIndex:4];
        [detailsModel.dataSource_head insertObject:string atIndex:4];
    }
    [self getFinderListRequest];

}
- (void)getFinderListRequest{
    [LSProgressHUD showLoadingToView:self.navigationController.view];
    NSDictionary *dic = @{@"projectId":shareData.product_Id};
    __block NSInteger wordCount = 0;
    __block NSInteger target_wordcom = 0;
    __block NSInteger fileCount = 0;
    [AvailableNetWorking postWithUrl:productDetail_connector params:dic successHandler:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *arr = responseObject[@"result"];
            for (NSDictionary *dic in arr) {
                wordCount += [dic[@"wordcount"] integerValue];
                target_wordcom += [dic[@"target_wordcom"] integerValue];
            }
            fileCount = arr.count;
            [detailsModel.dataSource_head replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:@"%zd",fileCount]];
            [detailsModel.dataSource_head replaceObjectAtIndex:2 withObject:[NSString stringWithFormat:@"%zd字",wordCount]];
            [detailsModel.dataSource_head replaceObjectAtIndex:3 withObject:[NSString stringWithFormat:@"%zd字",target_wordcom]];
            [self.tableView reloadData];
        }
        else{
        }
        [LSProgressHUD hideForView:self.navigationController.view];
    } falureHandler:^(NSError *error) {
        [LSProgressHUD hideForView:self.navigationController.view];
    }];
}

- (void)initlizeUserface{

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
}

- (void)back {
    [self.magicController.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return  6;
    }
    else if (section == 1){
    
        return 1;
    }
    else{
    
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        return 30*Radio;
    }
    else if (indexPath.section == 1){
        return MAX(50.0, _cellHeight[indexPath.section]);
    }
    else{
        return 130*Radio;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        return 50*Radio;
    }
    else if (section == 1){
        return 50*Radio;
    }
    else{
        return 15*Radio;
    }
}

- (void)tableView:(UITableView *)tableView updatedHeight:(CGFloat)height atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        _cellHeight[indexPath.section] = height;
    }
}

- (void)tableView:(UITableView *)tableView updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==1 && indexPath.row == 0) {
        detailsModel.remark = text;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0.001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        //编辑项目标题UI
        UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 50*Radio)];
        baseView.backgroundColor = [UIColor whiteColor];
        _productName = [[UITextView alloc]initWithFrame:CGRectMake(10*Radio, 8, Screen_Width-30*Radio-60*Radio, remark_height)];
        _productName.backgroundColor = [UIColor clearColor];
        _productName.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
        _productName.textColor = RGB(51, 51, 51, 1);
        _productName.delegate = self;
        _productName.scrollEnabled = YES;
        _productName.editable = NO;
        _productName.text = detailsModel.productName;
        [baseView addSubview:_productName];
        
        _edit = [UIButton buttonWithType:UIButtonTypeCustom];
        _edit.frame = CGRectMake(Screen_Width - 80*Radio, 15*Radio, 70*Radio, 20*Radio);
        [_edit addTarget:self action:@selector(editResponds) forControlEvents:UIControlEventTouchUpInside];
        [_edit setTitle:@"编辑" forState:UIControlStateNormal];
        [_edit setTitleColor:RGB(88, 195, 241, 1) forState:UIControlStateNormal];
        [_edit setImage:[UIImage imageNamed:@"详情编辑"] forState:UIControlStateNormal];
        _edit.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
        _edit.imageEdgeInsets = UIEdgeInsetsMake(0,-15,0,0);
        [baseView addSubview:_edit];
        
        UIView *dashedView = [[UIView alloc] initWithFrame:CGRectMake(15, 49*Radio, Screen_Width, 2)];
        dashedView.backgroundColor = [UIColor whiteColor];
        [baseView addSubview:dashedView];
        [self drawDashLine:dashedView lineLength:2 lineSpacing:1 lineColor:RGB(246, 246, 246, 1)];
        
        _penView = [[UIImageView alloc]initWithFrame:CGRectMake(-20, 15*Radio, 20*Radio, 20*Radio)];
        _penView.image = [UIImage imageNamed:@"详情编辑中"];
        [baseView addSubview:_penView];
        
        return baseView;
    }
    else if (section == 1){
        //编辑项目备注UI
        UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 40*Radio)];
        baseView.backgroundColor = [UIColor whiteColor];
        _projectRemark = [[UILabel alloc]initWithFrame:CGRectMake(15, 20*Radio, Screen_Width-100*Radio, 20*Radio)];
        _projectRemark.backgroundColor = [UIColor clearColor];
        _projectRemark.text = @"项目备注";
        _projectRemark.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
        _projectRemark.textColor = RGB(177, 177, 177, 1);
        [baseView addSubview:_projectRemark];
        
        _editF = [UIButton buttonWithType:UIButtonTypeCustom];
        _editF.frame = CGRectMake(Screen_Width - 80*Radio, 20*Radio, 70*Radio, 20*Radio);
        [_editF addTarget:self action:@selector(editRespondsRemark) forControlEvents:UIControlEventTouchUpInside];
        [_editF setTitle:@"编辑" forState:UIControlStateNormal];
        [_editF setTitleColor:RGB(88, 195, 241, 1) forState:UIControlStateNormal];
        [_editF setImage:[UIImage imageNamed:@"详情编辑"] forState:UIControlStateNormal];
        _editF.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
        _editF.imageEdgeInsets = UIEdgeInsetsMake(0,-15,0,0);
        [baseView addSubview:_editF];

        UIView *dashedView = [[UIView alloc] initWithFrame:CGRectMake(15, 10*Radio, Screen_Width, 2)];
        dashedView.backgroundColor = [UIColor whiteColor];
        [baseView addSubview:dashedView];
        [self drawDashLine:dashedView lineLength:2 lineSpacing:1 lineColor:RGB(246, 246, 246, 1)];

        _penViewF = [[UIImageView alloc]initWithFrame:CGRectMake(-20, 20*Radio, 20*Radio, 20*Radio)];
        _penViewF.image = [UIImage imageNamed:@"详情编辑中"];
        [baseView addSubview:_penViewF];
        
        return baseView;
    }
    else{
        
        UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 50*Radio)];
        baseView.backgroundColor = RGB(247, 247, 247, 1);
        return baseView;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        
        ProductDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:productDetailsCell];
        cell.titleName.textColor = RGB(51, 51, 51, 1);
        cell.infoLabel.textColor = RGB(51, 51, 51, 1);
        cell.titleName.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
        cell.infoLabel.font = [UIFont systemFontOfSize:FLEXIBLE(15)];

        cell.titleName.text = _titles[indexPath.row];
        if ([detailsModel.dataSource_head[indexPath.row] isEqualToString:@"(null)字"]) {
            cell.infoLabel.text = @"0字";
        }else{
            cell.infoLabel.text = detailsModel.dataSource_head[indexPath.row];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 1){
    
        ACEExpandableTextCell *cell = [tableView expandableTextCellWithId:@"cellId"];
        cell.text = detailsModel.remark.length == 0 ? @"没有备注" : detailsModel.remark;
        _textView = cell.textView;
        return cell;
    }
    else{
    
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        //自定义progress
        [cell addSubview:self.progressView_All];
        [cell addSubview:self.progressView_proofread];
        [cell addSubview:self.progressView_edit];
        [cell addSubview:self.progressView_translate];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}


#pragma mark -- private
- (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:lineColor.CGColor];
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [lineView.layer addSublayer:shapeLayer];
}

- (CGFloat)judgeNanMethodWithNum:(CGFloat)num{
    
    return isnan(num) ? 0 :num;
}

#pragma mark --event
//修改项目标题
- (void)editResponds{


    [UIView animateKeyframesWithDuration:0.2
                                   delay:0.0
                                 options:UIViewKeyframeAnimationOptionLayoutSubviews
                              animations:^{
                                  
                                  [_edit setHidden:YES];
                                  _productName.editable = YES;
                                  _productName.frame = CGRectMake(45, 8, Screen_Width-30*Radio-60*Radio, remark_height);
                                  _penView.frame = CGRectMake(15, 15*Radio, 20*Radio, 20*Radio);
                              }
                              completion:^(BOOL finished) {
                                  
                              }];
    [self setupSubmitButton];
    [_productName becomeFirstResponder];

}
- (void)setupSubmitButton {

    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.saveBt];
    self.magicController.navigationItem.rightBarButtonItem = item;
}


//修改项目备注
- (void)editRespondsRemark{
    [UIView animateKeyframesWithDuration:0.2
                                   delay:0.0
                                 options:UIViewKeyframeAnimationOptionLayoutSubviews
                              animations:^{
                                  
                                  [_editF setHidden:YES];
                                  _textView.editable = YES;
                                  _projectRemark.frame = CGRectMake(45, 20*Radio, Screen_Width-100*Radio, 20*Radio);
                                  _penViewF.frame = CGRectMake(15, 20*Radio, 20*Radio, 20*Radio);
                              }
                              completion:^(BOOL finished) {
                                  
                              }];
    [self setupSubmitButton];
    _textView.backgroundColor = [UIColor whiteColor];
    [_textView becomeFirstResponder];

}
//保存
- (void)saveClieced{

    [UIView animateKeyframesWithDuration:0.2
                                   delay:0.0
                                 options:UIViewKeyframeAnimationOptionLayoutSubviews
                              animations:^{
                                  
                                  _productName.frame = CGRectMake(15, 8, Screen_Width-30*Radio-60*Radio, remark_height);
                                  _penView.frame = CGRectMake(-20, 15*Radio, 20*Radio, 20*Radio);
                                  _projectRemark.frame = CGRectMake(15, 20*Radio, Screen_Width-100*Radio, 20*Radio);
                                  _penViewF.frame = CGRectMake(-20, 15*Radio, 20*Radio, 20*Radio);
                              }
                              completion:^(BOOL finished) {
                                  self.magicController.navigationItem.rightBarButtonItem = nil;
                                  _textView.editable = NO;
                                  _productName.editable = NO;
                                  [_edit setHidden:NO];
                                  [_editF setHidden:NO];
                                  [_textView resignFirstResponder];
                                  _textView.backgroundColor = [UIColor whiteColor];
                              }];
    
    [self modfityProject];

}

- (void)modfityProject {
    [LSProgressHUD showLoadingToView:self.magicController.navigationController.view];
    NSString *name = _productName.text == nil ? @"":_productName.text;
    NSString *remark = _textView.text == nil ? @"":_textView.text;
    NSDictionary *parameter = @{@"projectId":detailsModel.product_Id,@"projectName":name,@"remark":remark};
    
    [AvailableNetWorking postWithUrl:modifyProject_connector params:parameter successHandler:^(id responseObject) {
        if (!responseObject) {
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"修改失败！" andTitleColor:[UIColor whiteColor] andCancel:YES];
        }else{
            [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"修改成功！" andTitleColor:[UIColor whiteColor] andCancel:YES];
        }
        [LSProgressHUD hideForView:self.magicController.navigationController.view];
    } falureHandler:^(NSError *error) {
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"修改失败！" andTitleColor:[UIColor whiteColor] andCancel:YES];
        [LSProgressHUD hideForView:self.magicController.navigationController.view];
        
    }];
}

#pragma mark -- getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-110) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.scrollIndicatorInsets = _tableView.contentInset;
    }
    return _tableView;
}

- (ProgressViewOfProDD *)progressView_All{
    
    if (!_progressView_All) {
        NSString *percent = @"%";
        _progressView_All = [ProgressViewOfProDD initWithFrame:CGRectMake(10, 10, Screen_Width-15, 20)
                                                      progress:floorf([self judgeNanMethodWithNum:detailsModel.progress_all]*100)/100
                                                      barColor:RGB(103, 103, 103, 1)];
        _progressView_All.progressLabel.text = @"总进度";
        _progressView_All.progressDataLabel.text = [NSString stringWithFormat:@"%.0f%@",floorf([self judgeNanMethodWithNum:detailsModel.progress_all]*100),percent];
    }
    return _progressView_All;
    
}

- (ProgressViewOfProDD *)progressView_proofread{
    
    if (!_progressView_proofread) {
        NSString *percent = @"%";
        _progressView_proofread = [ProgressViewOfProDD initWithFrame:CGRectMake(10, 40, Screen_Width-15, 20)
                                                            progress:floorf([self judgeNanMethodWithNum:detailsModel.progress_prof]*100)/100
                                                            barColor:RGB(70, 212, 159, 1)];
        _progressView_proofread.progressLabel.text = @"校   对";
        _progressView_proofread.progressDataLabel.text = [NSString stringWithFormat:@"%.0f%@",floorf([self judgeNanMethodWithNum:detailsModel.progress_prof]*100),percent];;
    }
    return _progressView_proofread;
    
}

- (ProgressViewOfProDD *)progressView_edit{
    
    if (!_progressView_edit) {
        NSString *percent = @"%";
        _progressView_edit = [ProgressViewOfProDD initWithFrame:CGRectMake(10, 70, Screen_Width-15, 20)
                                                       progress:floorf([self judgeNanMethodWithNum:detailsModel.progress_edit]*100)/100
                                                       barColor:RGB(55, 180, 234, 1)];
        _progressView_edit.progressLabel.text = @"编   辑";
        _progressView_edit.progressDataLabel.text = [NSString stringWithFormat:@"%.0f%@",floorf([self judgeNanMethodWithNum:detailsModel.progress_edit]*100),percent];;
        
    }
    return _progressView_edit;
}

- (ProgressViewOfProDD *)progressView_translate{
    
    if (!_progressView_translate) {
        NSString *percent = @"%";
        _progressView_translate = [ProgressViewOfProDD initWithFrame:CGRectMake(10, 100, Screen_Width-15, 20)
                                                            progress:floorf([self judgeNanMethodWithNum:detailsModel.progress_trans]*100)/100
                                                            barColor:RGB(246, 130, 72, 1)];
        _progressView_translate.progressLabel.text = @"翻   译";
        _progressView_translate.progressDataLabel.text = [NSString stringWithFormat:@"%.0f%@",floorf([self judgeNanMethodWithNum:detailsModel.progress_trans]*100),percent];;
        
    }
    return _progressView_translate;
}

- (UIButton *)saveBt{

    if (!_saveBt) {
        _saveBt = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveBt.frame = CGRectMake(0, 0, 50, 20);
        [_saveBt addTarget:self action:@selector(saveClieced) forControlEvents:UIControlEventTouchUpInside];
        [_saveBt setTitle:@"保存" forState:UIControlStateNormal];
        [_saveBt setTitleColor:RGB(51, 51, 51, 1) forState:UIControlStateNormal];
        _saveBt.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _saveBt;
}

@end
